<script>
import { dictMixin } from '@/mixin/dict'

export default {
  name: 'AddPhysicalModel',
  mixins: [dictMixin],
  props: {
    // 请求参数
    requestParams: {
      type: Object,
      default: () => ({})
    },
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isAdd: true,
      formData: {
        arrayDataType: null,
        arrayLength: null
      },
      enumList: [],
      objectList: [],
      modelTypeList: [],
      modelFutureList: [],
      modelFieldTypeList: [],
      modelDataTypeList: [],
      showObjectDialog: false,
      objectDialogSearch: {},
      objectTableLoading: false,
      objectTable: {
        selectRow: {},
        total: 0,
        currentPage: 1,
        pageSize: 10,
        list: []
      }
    }
  },
  computed: {
    rules() {
      return {
        modelName: [
          { required: true, message: '请输入模型名称', trigger: 'blur' },
          { max: 50, message: '最长支持50个字符', trigger: 'blur' }
        ],
        modelTag: [
          { required: true, message: '请输入模型标识', trigger: 'blur' },
          { max: 50, message: '最长支持50个字符', trigger: 'blur' }
        ],
        modelType: [{ required: true, message: '请选择模型类别', trigger: 'blur' }],
        modelFeatures: [{ required: true, message: '请选择模型特性', trigger: 'blur' }],
        fieldType: [{ required: true, message: '请选择数据类型', trigger: 'blur' }],
        dataType: [{ required: true, message: '请选择数据类型', trigger: 'blur' }],
        minValue: [{ required: true, message: '请输入最小值', trigger: 'blur' }],
        maxValue: [{ required: true, message: '请输入最大值', trigger: 'blur' }],
        fixedValue: [{ required: true, message: '请输入额定值', trigger: 'blur' }],
        unit: [
          { required: true, message: '请输入单位', trigger: 'blur' },
          { max: 10, message: '单位不超过10字符', trigger: 'blur' }
        ],
        step: [{ required: true, message: '请输入步长', trigger: 'blur' }],
        falseValue: [
          { required: true, message: '请输入布尔值', trigger: 'blur' },
          { max: 10, message: '不超过10字符', trigger: 'blur' }
        ],
        trueValue: [
          { required: true, message: '请输入布尔值', trigger: 'blur' },
          { max: 10, message: '不超过10字符', trigger: 'blur' }
        ],
        maxLength: [{ required: true, message: '请输入最大长度', trigger: 'blur' }],
        arrayLength: [{ required: true, message: '请输入元素个数', trigger: 'blur' }],
        arrayDataType: [{ required: true, message: '请选择数组类型', trigger: 'blur' }]
      }
    }
  },
  watch: {
    popData: {
      async handler(data) {
        this.isAdd = !data.id
        if (!this.isAdd) {
          if (data.dataExtMap != null) {
            data = Object.assign({}, data, data.dataExtMap)
            delete data.dataExtMap
          }
          if (data.fieldType === '4') {
            this.enumList = data.enumList
          } else if (data.fieldType === '7') { // 对象
            const ids = data.objectList.map(item => item.id)
            if (ids.length > 0) {
              const list = await this.loadingDetailIds(ids)
              list.forEach(item => {
                const find = data.objectList.find(obj => item.id === obj.id)
                if (find) {
                  item.parameterName = find.parameterName
                }
              })
              this.objectList = list
            }
          }
          if (typeof data.modelFeatures === 'string') {
            data.modelFeatures = data.modelFeatures?.split(',')
          }
        }
        this.formData = data
      },
      deep: true,
      immediate: true
    },
    confirm() {
      const params = {
        ...(this.formData || {})
      }
      this.submit(params)
    }
  },
  created() {
    this.loadingInitData()
  },
  methods: {
    async loadingDetailIds(ids) {
      const res = await this.$api.physicalModel.detailByIds(ids)
      return res.data
    },
    objectDialogTableRowClick(row) {
      this.objectTable.selectRow = row
    },

    objectParamRemove(row) {
      this.objectList = this.objectList.filter(item => item.id !== row.id)
    },
    async objectDialogSearchHandler(page) {
      if (page == null) {
        page = 1
      }
      this.objectTableLoading = true
      const result = await this.$api.physicalModel.queryList({
        page: page,
        modelName: this.objectDialogSearch.modelName,
        limit: this.objectTable.pageSize
      })
      this.objectTable.total = result.data.total
      this.objectTable.currentPage = result.data.current
      this.objectTable.list = result.data.records
      this.objectTableLoading = false
    },
    async addObjectParamHandler() {
      this.showObjectDialog = true
      this.objectTableLoading = true
      const result = await this.$api.physicalModel.queryList({
        page: this.objectTable.currentPage,
        limit: this.objectTable.pageSize
      })
      this.objectTable.total = result.data.total
      this.objectTable.currentPage = result.data.current
      this.objectTable.list = result.data.records
      this.objectTableLoading = false
    },
    handleObjectTableSizeChange(limit) {
      this.objectTable.pageSize = limit
      this.handleObjectTableCurrentChange()
    },
    handleObjectTableCurrentChange(page) {
      this.objectDialogSearchHandler(page)
    },
    objectDialogConfirmHandler() {
      if (this.objectTable.selectRow.id) {
        this.objectTable.selectRow.parameterName = this.objectTable.selectRow.modelName
        this.objectList.push(this.objectTable.selectRow)
        this.objectTable.selectRow = {}
      }
      this.showObjectDialog = false

    },
    addEnumHandler() {
      this.enumList.push({
        value: null,
        label: null
      })
    },
    fieldTypeChangeHandler(value) {
      if (value === '4') { //enum
        this.addEnumHandler()
      } else if (value === '6') { // 数组
        if (this.formData.arrayLength == null) {
          this.formData.arrayLength = 5 //默认为5
        }
      }
    },
    async loadingInitData() {
      const modelTypeRes = await this.$api.commonSelected({ code: 'PhysicalModelModelType' })
      this.modelTypeList = modelTypeRes.data

      const modelFutureRes = await this.$api.commonSelected({ code: 'PhysicalModelModelFuture' })
      this.modelFutureList = modelFutureRes.data

      const modelFieldTypeRes = await this.$api.commonSelected({ code: 'PhysicalModelModelFieldType' })
      this.modelFieldTypeList = modelFieldTypeRes.data

      const modelDataTypeRes = await this.$api.commonSelected({ code: 'PhysicalModelModelDataType' })
      this.modelDataTypeList = modelDataTypeRes.data
    },
    /**
     * change事件
     */
    handlerSelectData(config) {
      const Ref = this.$refs[config.prop]
      if (Ref && config.isClosePop) {
        Ref.dropDownVisible = false
      }
    },
    /**
     * 提交
     */
    submit(params) {
      delete params.createTm
      delete params.modifyTm
      let extData = {}
      for (let key in params) {
        if (key === 'modelFeatures') {
          params.modelFeatures = params.modelFeatures.join(',')
        }
        const val = params[key]
        if (val != null &&
          (key === 'dataType' ||
            key === 'minValue' ||
            key === 'maxValue' ||
            key === 'fixedValue' ||
            key === 'unit' ||
            key === 'step' ||
            key === 'falseValue' ||
            key === 'trueValue' ||
            key === 'maxLength' ||
            key === 'arrayDataType' ||
            key === 'arrayLength'
          )) {
          extData[key] = val
        }
      }
      if (params.fieldType === '4') {
        extData.enumList = this.enumList
      } else if (params.fieldType === '7') {
        extData.objectList = this.objectList.map(item => {
          return {
            id: item.id,
            parameterName: item.parameterName
          }
        })
      }
      params.dataExt = JSON.stringify(extData)
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const res = await this.$api.physicalModel[
            this.isAdd ? 'add' : 'update'
            ](params)
          if (Number(res.code) === 1000) {
            this.$message.success(`${this.isAdd ? '新增' : '编辑'}成功！`)
            this.$emit('onFinish', 'physicalmodel-add')
          }
        }
      })
    }
  }
}
</script>

<template>
  <div class="physicalmodel-box">
    <el-form ref="form" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="模型名称" prop="modelName">
        <el-input v-model="formData.modelName" placeholder="请输入模型名称"></el-input>
      </el-form-item>
      <el-form-item label="模型标识" prop="modelTag">
        <el-input v-model="formData.modelTag" placeholder="请输入模型标识"></el-input>
      </el-form-item>
      <el-form-item label="模型类别" prop="modelType">
        <el-select v-model="formData.modelType" style="width: 100%">
          <el-option v-for="item in modelTypeList" :key="item.value" :label="item.label"
                     :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="模型特性" prop="modelFeatures">
        <el-select v-model="formData.modelFeatures" multiple style="width: 100%">
          <el-option v-for="item in modelFutureList" :key="item.value" :label="item.label"
                     :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据类型" prop="fieldType">
        <el-select v-model="formData.fieldType" style="width: 100%" @change="fieldTypeChangeHandler">
          <el-option v-for="item in modelFieldTypeList" :key="item.value" :label="item.label"
                     :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="formData.fieldType === '1' || formData.fieldType === '2' || formData.fieldType === '5'"
                    label="数据类型" prop="dataType">
        <el-radio-group v-model="formData.dataType" style="width: 100%">
          <el-radio v-for="item in modelDataTypeList" :key="item.value" :label="item.value"
                    :value="item.value">{{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-row v-if="(formData.fieldType === '1' || formData.fieldType === '2') && formData.dataType === '1'">
        <el-col :span="10">
          <el-form-item label="取值范围" prop="minValue">
            <el-input-number v-model="formData.minValue" :min="0" placeholder="最小值" />
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="到" prop="maxValue">
            <el-input-number v-model="formData.maxValue" :min="0" placeholder="最大值" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item v-else-if="(formData.fieldType === '1' || formData.fieldType === '2') && formData.dataType !== '1'"
                    label="额定值" prop="fixedValue">
        <el-input-number v-model="formData.fixedValue" :min="0" style="width: 100%" placeholder="请输入额定值" />
      </el-form-item>
      <el-form-item
        v-if="formData.fieldType === '1' || formData.fieldType === '2'"
        label="单位" prop="unit">
        <el-input v-model="formData.unit" placeholder="请输入单位,如: °C" />
      </el-form-item>
      <el-form-item v-if="(formData.fieldType === '1' || formData.fieldType === '2') && formData.dataType === '1'"
                    label="步长" prop="step">
        <el-input v-model="formData.step" placeholder="请输入步长，如1" />
      </el-form-item>
      <div class="bool" v-if="formData.fieldType === '3'">
        <el-form-item label="布尔值" prop="falseValue">
          <el-input v-model="formData.falseValue" placeholder="如: 关闭" style="width: 50%" />
          <span style="margin-left: 2px;">(0值对应文本)</span>
        </el-form-item>
        <el-form-item prop="trueValue">
          <el-input v-model="formData.trueValue" placeholder="如: 打开" style="width: 50%" />
          <span style="margin-left: 2px;">(1值对应文本)</span>
        </el-form-item>
      </div>
      <div class="enum" v-if="formData.fieldType === '4'">
        <el-row v-for="(item, index) in enumList" :key="index">
          <el-col :span="12">
            <el-form-item label="枚举项">
              <el-input v-model="item.value" placeholder="参数值，如: 0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-input v-model="item.label" placeholder="参数描述，如: 中速挡位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-left: 75px">
          <el-button type="text" @click="addEnumHandler">添加枚举项</el-button>
        </el-row>
      </div>
      <div class="string" v-if="formData.fieldType === '5'">
        <el-form-item label="最大长度" prop="maxLength">
          <el-input-number v-model="formData.maxLength" :min="0" placeholder="如: 1024" style="width: 100%" />
          <div>(字符串的最大长度）</div>
        </el-form-item>
      </div>
      <div class="array" v-if="formData.fieldType === '6'">
        <el-form-item label="元素个数" prop="arrayLength">
          <el-input-number v-model="formData.arrayLength" :min="0" placeholder="请输入元素个数" style="width: 100%" />
        </el-form-item>
        <el-form-item label="数组类型" prop="arrayDataType">
          <el-radio-group v-model="formData.arrayDataType">
            <el-radio value="1" label="1">整数</el-radio>
            <el-radio value="2" label="2">小数</el-radio>
            <el-radio value="5" label="5">字符串</el-radio>
            <el-radio value="7" label="7">对象</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <div class="obj" v-if="formData.fieldType === '7'">
        <el-row>
          <el-form-item label="对象参数">
            <el-button type="text" @click="addObjectParamHandler">添加参数</el-button>
          </el-form-item>
        </el-row>
        <el-form-item>
          <el-row v-for="item in objectList" :key="item.id">
            <el-col :span="5">{{ item.modelTag }}</el-col>
            <el-col :span="12">
              <el-input v-model="item.parameterName" placeholder="参数名称" />
            </el-col>
            <el-col :span="2">
              <el-button @click="() => objectParamRemove(item)" type="danger" size="mini" icon="el-icon-delete">
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </div>
    </el-form>
    <el-dialog :visible="showObjectDialog" title="添加参数"
               :modal="false" top="20vh"
               @close="() => this.showObjectDialog = false"
               destroy-on-close width="25%">
      <el-row>
        <el-col :span="12">
          <el-input v-model="objectDialogSearch.modelName" placeholder="请输入模型名称">
          </el-input>
        </el-col>
        <el-button @click="objectDialogSearchHandler" size="small" type="primary" icon="el-icon-search">搜索</el-button>
      </el-row>
      <el-row>
        <el-table :data="objectTable.list"
                  v-loading="objectTableLoading"
                  @row-click="objectDialogTableRowClick">
          <el-table-column prop="modelName" label="参数名称" />
          <el-table-column prop="modelTag" label="标识符" />
          <el-table-column prop="fieldTypeName" label="数据类型" />
          <el-table-column width="80">
            <template #default="scope">
              <el-radio class="radio" v-model="objectTable.selectRow.id" :label="scope.row.id"><span></span></el-radio>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination v-if="objectTable.total > 0"
                       background
                       @size-change="handleObjectTableSizeChange"
                       @current-change="handleObjectTableCurrentChange"
                       :current-page="objectTable.currentPage"
                       :page-sizes="[10, 30, 50, 100]"
                       :page-size="objectTable.pageSize"
                       layout="sizes, prev, pager, next, jumper"
                       :total="objectTable.total">
        </el-pagination>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="() =>　this.showObjectDialog = false">取 消</el-button>
        <el-button type="primary" @click="objectDialogConfirmHandler">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>
